<?php

class DefaultController extends Controller
{
        protected $_model;
        protected $_arrParam;
        protected $_actionMain;
        protected $_namespace;  
        protected $pages = 7;
         public function init() {
            parent::init();             
            $this->_arrParam['controller'] = Yii::app()->getController()->getId();
            $this->_actionMain = $this->_arrParam['controller'].'/index';
            $this->_namespace = $this->_arrParam['controller'] ;            
            $ssFilter = Yii::app()->session[$this->_namespace];                     
        }
	public function filters()
	{
		return array(
			'accessControl',
		);
	}
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',
				'actions'=>array('index', 'view', 'preview'),
				'users'=>array('*'),
			),
			array('allow',
				'actions'=>array('create', 'update', 'refresh', 'viewCreate', 'order', 'orderSuccess', 'preOrder'),
				'users'=>array('@'),
			),
			array('deny',
				'users'=>array('*'),
			),
		);
	}
	public function actionIndex($slug)
	{
        $model = Events::model()->findByAttributes(array('url'=>$slug));

        if (!empty($model)) {
            $this->redirect(array('/Events/default/view', 'category'=>$model->category->url, 'url'=>$model->url));
        }

        $this->redirect(array('/Home/default/index'));
	}

	public function actionPreview($category, $url)
	{
		$this->layout = '//layouts/eventsDefaultView';
		$criteria = new CDbCriteria;
		$criteria->condition = 't.url="' . $url . '"';
		$criteria->with = array('category'=>array(
			'joinType'=>'INNER JOIN',
			'condition'=>'category.url = "' . $category . '"'
		));
		$model = Events::model()->find($criteria);

		if (!empty($model)) {
			//
		}
		else {
			throw new CHttpException(404,'The requested page does not exist.');
		}

		// Events in category
		$criteria = new CDbCriteria;
		$criteria->condition = 't.id != ' . $model->id . ' AND t.status = "A" AND enddate >= NOW()';
		$criteria->limit = 5;
		$criteria->order = 'enddate ASC, startdate DESC';
		$criteria->with = array('category'=>array(
			'joinType'=>'INNER JOIN',
			'condition'=>'category.url = "' . $category . '"'
		));
		$events = Events::model()->findAll($criteria);

		$this->render('view', array(
			'model'=>$model,
			'events'=>$events
		));
	}

    public function actionView($category, $url)
	{        
		$this->layout = '//layouts/eventsDefaultView';
		$criteria = new CDbCriteria;
		$criteria->condition = 't.url="' . $url . '"';
		$criteria->with = array('category'=>array(
			'joinType'=>'INNER JOIN',
			'condition'=>'category.url = "' . $category . '"'
		));
		$model = Events::model()->find($criteria);                                
                $item_eo = $model->with('eventorganizers')->findAll($criteria); 
                foreach ( $item_eo[0]['eventorganizers'] as $key=>$value ){
                    $arr[] = $value->org_id;
                }         
                if( isset($arr) ){
                $criteriaeo = new CDbCriteria;
                $criteriaeo->addInCondition('id',$arr );                
                $organizers = Organizers::model()->findAll( $criteriaeo );
                }
                
		if (!empty($model)) {
			if ($model->status === 'P' || $model->status === 'D') {
				if ($model->member_id != Yii::app()->user->id) {
					throw new CHttpException(404,'The requested page does not exist.');
				}
			}
			else {
				// Update event number of views
				$model->updateByPk($model->id, array('numviews'=>$model->numviews+1));
			}
		}
		else {
			throw new CHttpException(404,'The requested page does not exist.');
		}

		// Events in category
		$criteria = new CDbCriteria;
		$criteria->condition = 't.id != ' . $model->id . ' AND t.status = "A" AND enddate >= NOW()';
		$criteria->limit = 5;
		$criteria->order = 'enddate ASC, startdate DESC';
		$criteria->with = array('category'=>array(
			'joinType'=>'INNER JOIN',
			'condition'=>'category.url = "' . $category . '"'
		));
		$events = Events::model()->findAll($criteria);
                
		$this->render('view', array(
			'model'=>$model,
                        'organizers'=>  empty($organizers)? null: $organizers,
			'events'=>$events
		));
	}                

	public function actionCreate()
	{
		$this->layout = '//layouts/eventsDefaultCreate';
		$model = new Events('create');
		$category = new EventCategories;
		$chart = new EventCharts;
		$contact = new EventContact;
		$content = new EventContent;
        $label = new Labels;
		$location = new EventLocations;
		$ticket = new EventTickets;

        $model->startdate = date('Y-m-d H:i:s', round(time() / (15 * 60)) * (15 * 60));
        $model->enddate = date('Y-m-d H:i:s', round((time() + 4 * 3600) / (15 * 60)) * (15 * 60));

		if (isset($_POST['Events'])) {
			$model->attributes = $_POST['Events'];
            $model->title = trim($model->title, ' ,.');
			$model->code = '';
			$model->othertitle = $model->title;
			$model->discount = 'N';
			$model->type = 'P';
			$model->numlike = 0;
			$model->numdislike = 0;
			$model->numviews = 0;
			$model->numcomments = 0;
			$model->hot = 'N';
			$model->featured = 'N';
			$model->homepage = 'N';
			$model->status = 'D';
			$model->url = $this->createSlug($model->title);
			$model->posteddate = date('Y-m-d H:i:s');
            $model->updatedate = date('Y-m-d H:i:s');
			$model->member_id = Yii::app()->user->id;
			// Save image here
			$imagePath = IMAGES_DIR . 'events/original/' . date('Ymd', strtotime($model->posteddate)) . '/';
			$imageUploadFile = CUploadedFile::getInstance($model, 'image');
            if ($model->title !== '') {
                if ($imageUploadFile !== null) {
                    $model->image = $model->url . '.' . $imageUploadFile->extensionName;
                    if (!file_exists($imagePath)) {
                        mkdir($imagePath, 0777, true);
                    }
                    $imageUploadFile->saveAs($imagePath . $model->image);
                    // Resize images
                    $this->resizeImage($imagePath, $model->image, date('Y-m-d H:i:s'));
                }
                else {
                    if (isset($_POST['Events']['currentImage'])) {
                        $image = $_POST['Events']['currentImage'];
                        $model->image = $model->url . '.' . pathinfo($image, PATHINFO_EXTENSION);
                        copy($imagePath . $image, $imagePath . $model->image);
                        // Resize images
                        $this->resizeImage($imagePath, $model->image, date('Y-m-d H:i:s'));
                    }
                }
            }
			// Save time here
			$startdate = explode('-', $_POST['startdate']);
			$model->startdate = $startdate['2'] . '-' . $startdate['1'] . '-' . $startdate['0'] . ' ' . $_POST['starttime'];
			$enddate = explode('-', $_POST['enddate']);
			$model->enddate = $enddate['2'] . '-' . $enddate['1'] . '-' . $enddate['0'] . ' ' . $_POST['endtime'];

			// Save the content
			$content->attributes = $_POST['EventContent'];
			/*
			$imagePath = IMAGES_DIR . 'contents/' . date('Ymd', strtotime($model->posteddate)) . '/';
			if (!file_exists($imagePath)) {
				mkdir($imagePath, 0777, true);
			}
			preg_match_all('/\<img(.*)src\=\"([^\"]+)\"(.*)\>/', $content->description, $matches, PREG_SET_ORDER);

			foreach ($matches as $key => $images) {
				// Save images
				$filePath = pathinfo($images[2]);
				$imageName = $model->url . '_' . ($key + 1) . '.' . $filePath['extension'];
				$fp = fopen($imagePath . $imageName, 'wb');
				fclose($fp);
				copy($images[2], $imagePath . $imageName);
				// Replace in content
				$content->description = str_replace($images[0], '<img src="/images/news/' . date('Ymd', strtotime($model->posteddate)) . '/' . $imageName . '" alt="' . $model->title . '" /><br />', $content->description);
			}
			*/
			$location->attributes = $_POST['EventLocations'];
            $location->event_id = 0;
            $location->place_id = 0;
            $location->location = 'N/A';
            $location->district_id = 0;
            $location->city_id = 0;
            $location->country_id = 0;
            $location->map = 'N/A';
            $location->phone = '';
            $location->altphone = '';
            $location->fax = '';
            $location->direction = '';
            // Get tags
            $tags = $_POST['Labels']['title'];
            $tags = explode(',', $tags);
            $labels = '';
            foreach ($tags as $data) {
                $temp = Labels::model()->findByPk($data);
                if (!empty($temp)) {
                    $labels .= $temp->id . ':' . $temp->title . ',';
                }
                else {
                    $labels .= $data . ':' . $data . ',';
                }
            }
            $labels = substr($labels, 0, -1);
            Yii::app()->session['tags'] = $labels;
			// Save event
			if ($model->validate() && $content->validate()) {
                $model->save();
				// Save category
				$category->event_id = $model->id;
				$category->category_id = $_POST['EventCategories']['category_id'];
				$category->isprimary = 'Y';
				$category->save();
				//Save chart
				$imageUploadFile = CUploadedFile::getInstance($chart, 'image');
				if ($imageUploadFile !== null) {
					$imageChartPath = IMAGES_DIR . 'events/charts/' . date('Ymd', strtotime($model->posteddate)) . '/';
					$chart->image = 'chart-' . $model->url . '.' . $imageUploadFile->extensionName;
					if (!file_exists($imageChartPath)) {
						mkdir($imageChartPath, 0777, true);
					}
					$imageUploadFile->saveAs($imageChartPath . $chart->image);
					// Resize images
					$this->resizeChartImage($imageChartPath, $chart->image, date('Y-m-d H:i:s'));
					$chart->event_id = $model->id;
					$chart->title = $model->title;
					if ($chart->validate()) {
						$chart->save();
					}
				}
				// Save contact
				foreach ($_POST['EventContact']['prename'] as $x => $data) {
					$xResult = array(
						'prename'=>$data,
						'company'=>$_POST['EventContact']['company'][$x],
						'fullname'=>$_POST['EventContact']['fullname'][$x],
						'phone'=>$_POST['EventContact']['phone'][$x],
					);

					$xData = new EventContact;
					$xData->attributes = $xResult;
					$xData->event_id = $model->id;
					$xData->agent_id = 0;
					$xData->email = 'N/A';
					$xData->altphone = '';
					$xData->address = 'N/A';
					$xData->brief = 'N/A';
					if ($xData->validate()) {
						$xData->save();
					}
					else {
						//break;
					}
				}
				// Save content
				$content->event_id = $model->id;
				$content->save();
				// Save location
				$location->event_id = $model->id;

				if ($location->validate()) {
					$location->save();
				}
				// Save ticket
				if ($model->ticket !== 'F') {
					foreach ($_POST['EventTickets']['title'] as $x => $data) {
						$xResult = array(
							'title'=>$data,
							'price'=>$_POST['EventTickets']['price'][$x],
						);

						$xData = new EventTickets;
						$xData->attributes = $xResult;
						$xData->event_id = $model->id;
						$xData->brief = '';
						$xData->quantity = 100;
						$xData->minorder = 1;
						$xData->maxorder = 10;
						$xData->priceoff = 0;
						$xData->percentoff = 0;
						$xData->startsale = date('Y-m-d H:i:s');
						$xData->endsale = date('Y-m-d H:i:s');
						$xData->position = 0;
						$xData->outofstock = 'N';
						$xData->status = 'D';
						if ($xData->validate()) {
							$xData->save();
						}
						else {
							//break;
						}
					}
				}

				// Save SEOTool
				$seotool = new SeoTools;
				$seotool->title = $model->title;
				$seotool->description = substr($model->brief, 0, 255);
				$seotool->keywords = '';
				$seotool->metarobot = '';
				$seotool->tables = 'events';
				$seotool->table_id = $model->id;
				$seotool->status = 'A';
				$seotool->posteddate = date('Y-m-d H:i:s');
				if ($seotool->validate()) {
					$seotool->save();
				}
                // Save tags
                foreach ($tags as $data) {
                    $temp1 = Labels::model()->findByPk($data);
                    if (!empty($temp1)) {
                        // Save label relation
                        $yData = new EventLabels;
                        $yData->event_id = $model->id;
                        $yData->label_id = $data;
                        $yData->type = 'E';
                        $yData->save();
                    }
                    else {
                        // Save new label
                        $xData = new Labels;
                        $xData->title = trim($data);
                        $xData->slug = $this->createSlug($data);
                        $xData->posteddate = $xData->updatedate = date('Y-m-d H:i:s');
                        $xData->save();
                        // Save label relation
                        $yData = new EventLabels;
                        $yData->event_id = $model->id;
                        $yData->label_id = $xData->id;
                        $yData->type = 'E';
                        $yData->save();
                    }
                }
                Yii::app()->session['tags'] = null;
				// View Event
				$this->redirect(array('/Events/default/viewCreate', 'id'=>$model->id));
			}
		}

		$this->render('create', array(
			'model'=>$model,
			'category'=>$category,
			'chart'=>$chart,
			'contact'=>$contact,
			'content'=>$content,
            'label'=>$label,
			'location'=>$location,
			'ticket'=>$ticket
		));
	}

	public function actionViewCreate($id)
	{
		$model = Events::model()->findByPk($id);

		$this->redirect(array('/Events/default/view', 'category'=>$model->category->url, 'url'=>$model->url));
	}

	public function actionUpdate($category, $url){
		$this->layout = '//layouts/eventsDefaultCreate';
		$criteria = new CDbCriteria;
		$criteria->condition = 't.url="' . $url . '" AND member_id=' . Yii::app()->user->id;
		$criteria->with = array('category'=>array(
			'joinType'=>'INNER JOIN',
			'condition'=>'category.url = "' . $category . '"'
		));
		$model = Events::model()->find($criteria);

		if (!isset($model)) {
			throw new CHttpException(404,'The requested page does not exist.');
		}

		$model->scenario = 'update';
		$chart = new EventCharts;
        $contact = new EventContact;
        $label = new Labels;

		if (isset($_POST['Events'])) {
			$model->attributes = $_POST['Events'];
            $model->title = trim($model->title, ' ,.');
			//$model->url = $this->createSlug($model->title);
            $model->updatedate = date('Y-m-d H:i:s');
            $model->status = 'P';
			// Save image here
			$imagePath = IMAGES_DIR . 'events/original/' . date('Ymd', strtotime($model->posteddate)) . '/';
			$imageUploadFile = CUploadedFile::getInstance($model, 'image');

			$model->image = $model->url . '.' . pathinfo($model->image, PATHINFO_EXTENSION);
            // Kiểm tra nếu có upload file mới
			if ($model->title !== '') {
                if ($imageUploadFile !== null) {
                    $model->image = $model->url . '.' . $imageUploadFile->extensionName;
                    if (!file_exists($imagePath)) {
                        mkdir($imagePath, 0777, true);
                    }
                    $imageUploadFile->saveAs($imagePath . $model->image);
                    // Resize images
                    $this->resizeImage($imagePath, $model->image, $model->posteddate);
                }
                else {// Change file name nếu không thay đổi
                    if ($model->image !== $model->url . '.' . pathinfo($model->image, PATHINFO_EXTENSION)) {
                        copy($imagePath . $model->image, $imagePath . $model->url . '.' . pathinfo($model->image, PATHINFO_EXTENSION));
                        unlink($imagePath . $model->image);
                        $model->image = $model->url . '.' . pathinfo($model->image, PATHINFO_EXTENSION);
                        // Resize images
                        $this->resizeImage($imagePath, $model->image, $model->posteddate);
                    }
                }
            }

			// Save time here
			$startdate = explode('-', $_POST['startdate']);
			$model->startdate = $startdate['2'] . '-' . $startdate['1'] . '-' . $startdate['0'] . ' ' . $_POST['starttime'];
			$enddate = explode('-', $_POST['enddate']);
			$model->enddate = $enddate['2'] . '-' . $enddate['1'] . '-' . $enddate['0'] . ' ' . $_POST['endtime'];

			// Save the content
			$model->content->attributes = $_POST['EventContent'];

			// Save event
			if ($model->validate() && $model->save()) {
				// Save category
				$model->eventCategory->category_id = $_POST['EventCategories']['category_id'];
				$model->eventCategory->save();
				//Save chart
				$imageChartPath = IMAGES_DIR . 'events/charts/' . date('Ymd', strtotime($model->posteddate)) . '/';
				$imageUploadFile = CUploadedFile::getInstance($chart, 'image');
				if ($imageUploadFile !== null) {
					if (isset($model->chart)) {
						$model->chart->image = 'chart-' . $model->url . '.' . $imageUploadFile->extensionName;
						if (!file_exists($imageChartPath)) {
							mkdir($imageChartPath, 0777, true);
						}
						$imageUploadFile->saveAs($imageChartPath . $model->chart->image);
						// Resize images
						$this->resizeChartImage($imageChartPath, $chart->image, date('Y-m-d H:i:s'));
						$model->chart->title = $model->title;
						if ($model->chart->validate()) {
							$model->chart->save();
						}
					}
					else {
						$chart->image = 'chart-' . $model->url . '.' . $imageUploadFile->extensionName;
						if (!file_exists($imageChartPath)) {
							mkdir($imageChartPath, 0777, true);
						}
						$imageUploadFile->saveAs($imageChartPath . $chart->image);
						// Resize images
						$this->resizeChartImage($imageChartPath, $chart->image, date('Y-m-d H:i:s'));
						$chart->event_id = $model->id;
						$chart->title = $model->title;
						if ($chart->validate()) {
							$chart->save();
						}
					}
				}
				// Save contact
				foreach ($_POST['EventContact']['prename'] as $x => $data) {
					$xResult = array(
						'prename'=>$data,
						'company'=>$_POST['EventContact']['company'][$x],
						'fullname'=>$_POST['EventContact']['fullname'][$x],
						'phone'=>$_POST['EventContact']['phone'][$x],
					);

					if (isset($_POST['EventContact']['id'][$x])) {
						$xData = EventContact::model()->findByPk($_POST['EventContact']['id'][$x]);
						$xData->attributes = $xResult;
						if ($xData->validate()) {
							$xData->save();
						}
						else {
							//break;
						}
					}
					else {
						$xData = new EventContact;
						$xData->attributes = $xResult;
						$xData->event_id = $model->id;
						$xData->agent_id = 0;
						$xData->email = 'N/A';
						$xData->altphone = '';
						$xData->address = 'N/A';
						$xData->brief = 'N/A';
						if ($xData->validate()) {
							$xData->save();
						}
						else {
							//break;
						}
					}
				}
				// Save content
				if ($model->content->validate()) {
					$model->content->save();
				}
				// Save location
				$model->location->attributes = $_POST['EventLocations'];

				if ($model->location->validate()) {
					$model->location->save();
				}
				// Save ticket
				if ($model->ticket === 'F') {
					if (!empty($model->tickets)) {
						foreach ($model->tickets as $data) {
							$data->delete();
						}
					}
				}
				else {
					foreach ($_POST['EventTickets']['title'] as $x => $data) {
						$xResult = array(
							'title'=>$data,
							'price'=>$_POST['EventTickets']['price'][$x],
						);

						if (isset($_POST['EventTickets']['id'][$x])) {
							$xData = EventTickets::model()->findByPk($_POST['EventTickets']['id'][$x]);
							$xData->attributes = $xResult;
							if ($xData->validate()) {
								$xData->save();
							}
							else {
								//break;
							}
						}
						else {
							$xData = new EventTickets;
							$xData->attributes = $xResult;
							$xData->event_id = $model->id;
							$xData->brief = '';
							$xData->quantity = 100;
							$xData->minorder = 1;
							$xData->maxorder = 10;
							$xData->priceoff = 0;
							$xData->percentoff = 0;
							$xData->startsale = date('Y-m-d H:i:s');
							$xData->endsale = date('Y-m-d H:i:s');
							$xData->position = 0;
							$xData->outofstock = 'N';
							$xData->status = 'A';
							if ($xData->validate()) {
								$xData->save();
							}
							else {
								//break;
							}
						}
					}
				}
				// Save SEOTool
				$model->seotool->title = $model->title;
				$model->seotool->description = $model->brief;
				$model->seotool->keywords = '';
				$model->seotool->metarobot = '';
				if ($model->seotool->validate()) {
					$model->seotool->save();
				}
                // Save tags
                $tags = $_POST['Labels']['title'];
                $tags = explode(',', $tags);
                $tagsList = array();
                foreach ($tags as $data) {
                    $temp1 = Labels::model()->findByPk($data);
                    if (!empty($temp1)) {
                        $tagsList[] = $data;
                        $temp2 = EventLabels::model()->findByAttributes(array('label_id'=>$data, 'event_id'=>$model->id));
                        if (empty($temp2)) {
                            // Save label relation
                            $yData = new EventLabels;
                            $yData->event_id = $model->id;
                            $yData->label_id = $data;
                            $yData->type = 'E';
                            $yData->save();
                        }
                    }
                    else {
                        // Save new label
                        $xData = new Labels;
                        $xData->title = trim($data);
                        $xData->slug = $this->createSlug($data);
                        $xData->posteddate = $xData->updatedate = date('Y-m-d H:i:s');
                        $xData->save();
                        $tagsList[] = $xData->id;
                        // Save label relation
                        $yData = new EventLabels;
                        $yData->event_id = $model->id;
                        $yData->label_id = $xData->id;
                        $yData->type = 'E';
                        $yData->save();
                    }
                }
                foreach ($model->label as $data) {
                    if (!in_array($data->id, $tagsList)) {
                        EventLabels::model()->findByAttributes(array('event_id'=>$model->id, 'label_id'=>$data->id))->delete();
                    }
                }
				// View Event
				$this->redirect(array('/Events/default/view', 'category'=>$model->category->url, 'url'=>$model->url));
			}
		}

		if (empty($model)) {
			throw new CHttpException(404,'The requested page does not exist.');
		}

		$this->render('update', array(
			'model'=>$model,
			'chart'=>$chart,
            'contact'=>$contact,
            'label'=>$label,
		));
	}

    public function actionRefresh($category, $url)
    {
        $criteria = new CDbCriteria;
		$criteria->condition = 't.url="' . $url . '" AND member_id=' . Yii::app()->user->id;
		$criteria->with = array('category'=>array(
			'joinType'=>'INNER JOIN',
			'condition'=>'category.url = "' . $category . '"'
		));
		$model = Events::model()->find($criteria);

		if (!isset($model)) {
			throw new CHttpException(404,'The requested page does not exist.');
		}

        $model->updatedate = date('Y-m-d H:i:s');
        $model->save();

        $this->redirect(array('/Users/profiles/eventMe', 'id'=>Yii::app()->user->id));
    }

    public function actionOrder($category, $url)
    {
        $this->layout = '//layouts/eventsDefaultOrder';
        $criteria = new CDbCriteria;
		$criteria->condition = 't.url="' . $url . '"';
		$criteria->with = array('category'=>array(
			'joinType'=>'INNER JOIN',
			'condition'=>'category.url = "' . $category . '"'
		));
		$model = Events::model()->find($criteria);

		if (!isset($model)) {
			throw new CHttpException(404,'The requested page does not exist.');
		}
        // Create some tables record
        $order = new Orders;
        $orderBuyer = new OrderBuyers;
        $orderReceiver = new OrderReceivers;
        $orderTicket = new OrderTickets;

        $this->performAjaxValidation($orderBuyer);
        $this->performAjaxValidation($orderTicket);
        $user = Members::model()->findByPk(Yii::app()->user->id);

        if (isset($_POST['Orders'],$_POST['OrderBuyers'],$_POST['OrderReceivers'])) {
        	$order->attributes = $_POST['Orders'];
			$orderBuyer->attributes = $_POST['OrderBuyers'];
			$orderReceiver->attributes = $_POST['OrderReceivers'];

            $order->subtotal = '';
            $order->total = '';
            $order->procode = '';
            $order->paymenttype = 'N';
            $order->status = 'D';
            $order->orderdate = date('Y-m-d H:i:s');

            $orderBuyer->order_id = 0;
            $orderBuyer->district_id = 0;
            $orderBuyer->city_id = 0;
            $orderBuyer->country_id = 0;
            $orderBuyer->fax = '';
            $orderBuyer->saveinfo = 'N';
            if(empty($_POST['OrderBuyers']['altphone'])){
            	$orderBuyer->altphone = '';
            }

            $orderReceiver->order_id = 0;
            $orderReceiver->district_id = 0;
            $orderReceiver->city_id = 0;
            $orderReceiver->country_id = 0;
            $orderReceiver->fax = '';
            if(empty($_POST['OrderReceivers']['altphone'])){
            	$orderReceiver->altphone = '';
            }
            $orderReceiver->receivedate = date('Y-m-d H:i:s');

            if ($order->validate() && $orderBuyer->validate() && $orderReceiver->validate()) {
                $order->save();
                // Update Buyer
                $orderBuyer->order_id = $order->id;
                $orderBuyer->save();
                // Update Receiver
                $orderReceiver->order_id = $order->id;
                $orderReceiver->save();
                // Ticket
                if (isset($_POST['OrderTickets'])) {
                    foreach ($_POST['OrderTickets']['ticket_id'] as $x => $ticket) {
                        $xData = new OrderTickets;
                        $xData->order_id = $order->id;
                        $xData->ticket_id = $ticket;
                        $xData->price = str_replace('.', '', $_POST['OrderTickets']['price'][$x]);
                        $xData->priceoff = 0;
                        $xData->percentoff = 0;
                        $xData->quantity = $_POST['OrderTickets']['quantity'][$x];
                        if ($xData->quantity > 0) {
                            $xData->save();
                        }
                    }
                }else{
                		$xData = new OrderTickets;
                        $xData->order_id = $order->id;
                        $xData->ticket_id = $model->id;
                        $xData->price = '';
                        $xData->priceoff = 0;
                        $xData->percentoff = 0;
                        $xData->quantity = 0;
                        $xData->save();
                }
                // Redirect
                $this->redirect(array('/Events/default/orderSuccess', 'id'=>$order->id));
            }
        }

        $this->render('order', array(
            'model'=>$model,
            'order'=>$order,
            'orderBuyer'=>$orderBuyer,
            'orderReceiver'=>$orderReceiver,
            'orderTicket'=>$orderTicket,
            'user'=>$user
        ));
    }

    public function actionOrderSuccess($id)
    {
        $this->layout = '//layouts/eventsDefaultOrder';
        $model = Orders::model()->findByAttributes(array('id'=>$id, 'member_id'=>Yii::app()->user->id));

        if (!isset($model)) {
			throw new CHttpException(404,'The requested page does not exist.');
		}

        $this->render('orderSuccess', array(
            'model'=>$model
        ));
    }

    public function actionPreOrder($id)
    {
        $model = Events::model()->findByPk($id);

        if (!isset($model)) {
			throw new CHttpException(404,'The requested page does not exist.');
		}

        foreach ($_POST['SeatTickets'] as $x=>$data) {
            foreach ($data as $id) {
                echo $x . ' - ' . $id . '<br/>';
            }
        }

        //$this->redirect(array('/Events/default/order', 'category'=>$model->category->url, 'url'=>$model->url));
    }

    protected function performAjaxValidation($model)
	{
    if(isset($_POST['ajax']) && $_POST['ajax']==='order-form')
    {
        echo CActiveForm::validate($model);
        Yii::app()->end();
    }
	}
}